//
//  OrderDetailController.swift
//  订单详情界面
//
//  Created by smile on 2019/7/19.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//导入发布订阅框架
import SwiftEventBus

//导入日志框架
import CocoaLumberjack

class OrderDetailController: BaseTitleController {
    
    /// 支付成功后显示的信息
    @IBOutlet weak var lbPaySuccess: UILabel!
    
    /// 订单号
    @IBOutlet weak var lbNumber: UILabel!
    
    /// 订单号
    @IBOutlet weak var lbStatus: UILabel!
    
    /// 商品封面
    @IBOutlet weak var ivBanner: UIImageView!
    
    /// 商品标题
    @IBOutlet weak var lbTitle: UILabel!
    
    @IBOutlet weak var lbCreatedAt: UILabel!
    
    /// 订单来源
    @IBOutlet weak var lbSource: UILabel!
    
    /// 支付来源
    @IBOutlet weak var lbOrigin: UILabel!
    
    /// 支付渠道
    @IBOutlet weak var lbChannel: UILabel!
    
    /// 支付渠道容器
    @IBOutlet weak var svPayMethodContainer: UIStackView!
    
    /// 支付宝选中状态图片控件
    @IBOutlet weak var ivAlipay: UIImageView!
    
    /// 微信选中状态图片控件
    @IBOutlet weak var ivWechat: UIImageView!
    
    /// 支付宝容器
    @IBOutlet weak var svAlipay: UIStackView!
    
    /// 微信容器
    @IBOutlet weak var svWechat: UIStackView!
    
    /// 价格
    @IBOutlet weak var lbPrice: UILabel!
    
    /// 支付按钮容器
    @IBOutlet weak var lbPayContainer: UIStackView!
    
    /// Id
    var id:String!
    
    /// 订单
    var data:Order!
    
    /// 支付渠道
    /// 默认是支付宝支付
    var channel:Order.Channel = .alipay
    
    /// 是否通知支付状态
    var isNotifyPayStatus = false
    
    override func initViews() {
        super.initViews()
        
        setTitle("订单详情")
    }
    
    override func initDatas() {
        super.initDatas()
        
        fetchData()
    }
    
    func fetchData() {
        Api.shared.orderDetail(id).subscribeOnSuccess { (data) in
            if let data=data?.data{
                self.showData(data)
            }
        }.disposed(by: disposeBag)
    }
    
    override func initListeners() {
        super.initListeners()
        
        //支付宝点击
        svAlipay.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onAlipayClick)))
        
        //微信点击
        svWechat.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onWechatClick)))
        
        //监听支付宝支付结果
        SwiftEventBus.onMainThread(self, name: ON_ALIPAY_CALLBACK) { (sender) in
            let data=sender!.object as! [String:Any]
            
            //处理支付宝支付结果
            self.processAlipayResult(data)
        }
        
        //监听微信支付支付结果
        SwiftEventBus.onMainThread(self, name: ON_WECHATA_PAY_CALLBACK) { (sender) in
            let data = sender!.object as! PayResp
            
            //处理微信支付结果
            self.processWechatPayResult(data)
        }
    }
    
    /// 处理支付宝支付结果
    ///
    /// - Parameter data: <#data description#>
    func processAlipayResult(_ data:[String:Any]) {
        let resultStatus = data["resultStatus"] as! String
        
//        if resultStatus == "9000" {
        if false {
            //本地支付成功
            
            checkPayStatus()
        }else {
            showPayFailedHint()
        }
    }
    
    /// 处理微信支付结果
    /// - Parameter data: <#data description#>
    func processWechatPayResult(_ data:PayResp) {
        if data.errCode == WXSuccess.rawValue {
            //本地支付成功
            
            //去服务端检查支付结果
            checkPayStatus()
        } else {
            showPayFailedHint()
        }
    }
    
    
    /// 去服务端检查支付结果
    func checkPayStatus() {
        //不能依赖本地支付结果
        //一定要以服务端为准
        ToastUtil.showLoading("支付确认中，请稍后.")
        
        //延时3秒
        //因为支付宝回调我们服务端可能有延迟
        DispatchQueue.main.asyncAfter(deadline: .now()+3.0) {
            self.next()
        }
        
        //这里就不根据服务端判断了
        //购买成功统计
        AnalysisUtil.onPurchase(true, self.data)
    }
    
    /// 显示支付失败提示
    func showPayFailedHint() {
        //可能是取消了
        //支付失败
        
        ToastUtil.short("支付失败，请稍后再试！")
        
        //购买失败统计
        AnalysisUtil.onPurchase(false, self.data)
    }
    
    /// 下一步
    /// 确认订单是否支付成功
    /// 本地回调的成功只是界面做处理
    /// 具体是否支付成功以服务端为准
    func next() {
        isNotifyPayStatus=true

        print("OrderDetailController next")
        
        ToastUtil.hideLoading()
        
        //请求订单详情
        fetchData()
    }
    
    /// 支付宝点击
    @objc func onAlipayClick() {
        print("OrderDetailController onAlipayClick")
        
        //选中支付宝
        ivAlipay.image=UIImage(named: "CheckBoxSelected")
        
        //取消选中微信
        ivWechat.image=UIImage(named: "CheckBox")
        
        //将支付渠道设置为支付宝
        channel = .alipay
    }
    
    /// 微信点击
    @objc func onWechatClick() {
        print("OrderDetailController onWechatClick")
        
        //取消选中支付宝
        ivAlipay.image=UIImage(named: "CheckBox")
        
        //选中微信
        ivWechat.image=UIImage(named: "CheckBoxSelected")
        
        //将支付渠道设置为微信
        channel = .wechat
    }
    
    /// 显示数据
    ///
    /// - Parameter data: <#data description#>
    func showData(_ data:Order)  {
        self.data=data
        
        print("OrderDetailController showData:\(data.book.title)")
        
        //订单号
        lbNumber.text=data.number
        
        //商品图片
        ImageUtil.show(ivBanner, data.book.banner)
        
        //商品标题
        lbTitle.text=data.book.title
        
        //创建日期
        lbCreatedAt.text="下单日期：\(TimeUtil.date2yyyyMMddHHmmss(data.created_at))"
        
        //订单来源
        lbSource.text="订单来源：\(data.formatSource)"
        
        //价格
        lbPrice.text="￥\(String(data.price))"
        
        //显示订单状态
        showOrderStatus(data)
    }
    
    /// 显示订单状态
    ///
    /// - Parameter data: <#data description#>
    func showOrderStatus(_ data:Order) {
        //订单状态
        lbStatus.text=data.formatStatus
        
        //支付来源
        lbOrigin.text="支付来源：\(data.formatOrigin)"
        
        //支付渠道
        lbChannel.text="支付渠道：\(data.formatChannel)"
        
        switch data.status {
        case .payed:
            //支付成功
            lbStatus.textColor=UIColor(named: "ColorPass")
            
            //显示支付成功提示
            lbPaySuccess.isHidden=false
            
            //隐藏支付渠道
            svPayMethodContainer.isHidden=true
            
            //隐藏支付控制容器
            lbPayContainer.isHidden=true
            
            if isNotifyPayStatus{
                //发送支付成功通知
                SwiftEventBus.post(ON_PAY_SUCCESS)
                
                isNotifyPayStatus=false
            }
        case .close:
            //订单关闭
            
            //隐藏支付渠道
            svPayMethodContainer.isHidden=true
            
            //隐藏支付控制容器
            lbPayContainer.isHidden=true
        default:
            //等待支付
            
            //显示支付渠道
            svPayMethodContainer.isHidden=false
            
            //显示支付控制容器
            lbPayContainer.isHidden=false
        }
    }
    
    
    /// 支付点击
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onPayClick(_ sender: Any) {
        print("OrderDetailController onPayClick")
        
//        processAlipay("替换成支付宝支付参数")
        
        fetchPayData()
    }
    
    /// 获取支付参数
    func fetchPayData() {
        Api.shared.orderPay(id, channel.rawValue).subscribeOnSuccess { (data) in
            if let data=data?.data{
                self.processPay(data)
            }
        }.disposed(by: disposeBag)
    }
    
    /// 处理支付
    ///
    /// - Parameter data: <#data description#>
    func processPay(_ data:Pay) {
        switch data.channel! {
        case .alipay:
            //支付宝支付
            processAlipay(data.pay!)
        case .wechat:
            //微信支付
            processWechat(data.wechatPay!)
        default:
            ToastUtil.short("支付渠道错误，请稍后再试！")
        }
    }
    
    /// 微信支付
    ///
    /// - Parameter data: <#data description#>
    func processWechat(_ data:WechatPay) {
        //把服务端返回的参数
        //设置到对应的字段
        let request = PayReq()
        request.partnerId = data.partnerid
        request.prepayId = data.prepayid
        request.nonceStr = data.noncestr
        request.timeStamp = UInt32(data.timestamp)!
        request.package = data.package
        request.sign = data.sign
        
        WXApi.send(request) { data in
            DDLogDebug("OrderDetailController processWechat \(data)")
        }
    }
    
    /// 支付宝支付
    ///
    /// - Parameter data: <#data description#>
    func processAlipay(_ data:String) {
        //支付宝官方开发文档：https://docs.open.alipay.com/204/105295/
        AlipaySDK.defaultService()!.payOrder(data, fromScheme: ALIPAY_CALLBACK_SCHEME) { (data) in
            print("OrderDetailController processAlipay callback:\(data)")
            
            //如果手机中没有安装支付宝客户端
            //会跳转H5支付页面
            //支付相关的信息会通过这个方法回调
            
            //处理支付宝支付结果
            self.processAlipayResult(data as! [String : Any])
        }
    }
    
    /// 启动方法
    ///
    /// - Parameters:
    ///   - nav: <#nav description#>
    ///   - id: <#id description#>
    static func start(_ nav:UINavigationController,_ id:String) {
        //创建控制器
        let controller=nav.storyboard!.instantiateViewController(withIdentifier: "OrderDetail") as! OrderDetailController
        
        //传递数据
        controller.id=id
        
        //将控制添加到导航控制器中
        nav.pushViewController(controller, animated: true)
    }

    deinit {
        DDLogDebug("OrderDetailController deinit")
    }
}
